package org.jeecg.modules.monitoring.j_monitoring.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.RealSoftUser;
import org.jeecg.modules.monitoring.j_monitoring.entity.software.*;
import org.jeecg.modules.monitoring.j_monitoring.mapper.LicenseSoftwareMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.RealSoftUserMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.SoftwareModuleSettingMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.ILicenseSoftwareService;
import org.jeecg.modules.monitoring.j_monitoring.service.ISoftwareModuleSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Description: license_software
 * @Author: xiaoyq
 * @Date: 2023-09-05
 * @Version: V1.0
 */
@Service
public class LicenseSoftwareServiceImpl extends ServiceImpl<LicenseSoftwareMapper, LicenseSoftware> implements ILicenseSoftwareService {

    @Autowired
    private Environment env;

    @Autowired
    private ISoftwareModuleSettingService softwareModuleSettingService;

    @Resource
    private SoftwareModuleSettingMapper moduleSettingMapper;

    @Resource
    private RealSoftUserMapper realSoftUserMapper;

    // 累计访问
    private Integer allVisitNum = 0;

    // 本月访问
    private Integer monthVisitNum = 0;


    public ModelUsed modelUsed(String softwareName) {
        ModelUsed modelUsed = new ModelUsed();
        List<LicenseRealtimedataAllcompany> list = baseMapper.modelUsed(softwareName);

        if (list.size() == 0) {
            return modelUsed;
        }
        LicenseSoftware software = this.getOne(new QueryWrapper<LicenseSoftware>().lambda().eq(LicenseSoftware::getSoftwarename,softwareName));
        if(software==null){
            return modelUsed;
        }

        QueryWrapper<SoftwareModuleSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SoftwareModuleSetting::getSoftwareid,software.getId()).eq(SoftwareModuleSetting::getIsshow,1);
        queryWrapper.select("licensename");//许可名称
        List<String> showModules = softwareModuleSettingService.listObjs(queryWrapper,Object::toString);

        LicenseRealtimedataAllcompany allcompany = list.get(0);
        String dataValue = allcompany.getDatavalue();
        String[] dataValueArr = dataValue.split("==\\?");

        String[] modelList = dataValueArr[2].split(",");// 模块列表-应该是许可名称
        List<Integer> AllList = Arrays.stream(dataValueArr[3].split(",")).map(Integer::parseInt).collect(Collectors.toList());// 部署数
        List<Integer> useList = Arrays.stream(dataValueArr[4].split(",")).map(Integer::parseInt).collect(Collectors.toList());// 使用数

        List<Integer> resAllList = new ArrayList<>();
        List<Integer> resUseList = new ArrayList<>();
        List<String> resNameList = new ArrayList<>();
        for (int i = 0; i <= modelList.length-1 ; i++) {
            if(showModules.size()==0 || showModules.indexOf(modelList[i])!=-1){
                resAllList.add(AllList.get(i));
                resUseList.add(useList.get(i));
                resNameList.add(modelList[i]);
            }
        }

        modelUsed.setNameList(resNameList);
        modelUsed.setAllCountList(resAllList);
        modelUsed.setUseCountList(resUseList);
        return modelUsed;
    }


    public UsedFrequency usedFrequency(String softwareName, String place) {
        UsedFrequency usedFrequency = new UsedFrequency();

        String year = String.valueOf(DateUtils.getYear());
        String countField = getCountField(place);

        usedFrequency.setMonthList(DateUtils.getYearAllMonth());

        FrequencyCount frequencyCount = baseMapper.usedFrequency(countField, year, softwareName);

        List<Integer> countList = new ArrayList<>();
        frequencyCount = frequencyCount == null ? new FrequencyCount() : frequencyCount;
        countList.add(frequencyCount.getOne());
        countList.add(frequencyCount.getTwo());
        countList.add(frequencyCount.getThree());
        countList.add(frequencyCount.getFour());
        countList.add(frequencyCount.getFive());
        countList.add(frequencyCount.getSix());
        countList.add(frequencyCount.getSeven());
        countList.add(frequencyCount.getEight());
        countList.add(frequencyCount.getNine());
        countList.add(frequencyCount.getTen());
        countList.add(frequencyCount.getEleven());
        countList.add(frequencyCount.getTwelve());
        usedFrequency.setCountList(countList);
        return usedFrequency;
    }

    public String getCountField(String place) {
        switch (place) {
            case "北京":
                return "BJ";
            case "天津":
                return "TJ";
            case "上海":
                return "SH";
            case "深圳":
                return "SZ";
            case "湛江":
                return "ZJ";
            case "国际":
                return "GJ";
            case "非常规油气":
                return "FCGYQ";
            case "其他":
                return "QT";
            case "海油发展":
                return "HYFZ";
            default:
                return "BJ";
        }
    }

    public List<RealSoftUser> softUser(String softwareName) {

        return realSoftUserMapper.selectAll();
//        List<SoftUser> softUserList = new ArrayList<>();
//
//
////        SoftUserCount softUserCount = new SoftUserCount();
////        if(!"prod".equals(env.getProperty("spring.profiles.active"))){
////            softUserCount = baseMapper.softUserMysql(softwareName);
////        }else{
////            softUserCount = baseMapper.softUser(softwareName);
////        }
//
////        softUserCount = softUserCount == null ? new SoftUserCount() : softUserCount;
//        List<SoftUserDetails> userDetails = baseMapper.softUserDetails(softwareName);
//
//
//        SoftUser user = new SoftUser();
//        user.setName("北京分公司");
////        user.setFrequency(softUserCount.getBj());
//        user.setUserCount(this.getUserCount(userDetails,"北京"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("天津分公司");
////        user.setFrequency(softUserCount.getTj());
//        user.setUserCount(this.getUserCount(userDetails,"天津"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("上海分公司");
////        user.setFrequency(softUserCount.getSh());
//        user.setUserCount(this.getUserCount(userDetails,"上海"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("深圳分公司");
////        user.setFrequency(softUserCount.getSz());
//        user.setUserCount(this.getUserCount(userDetails,"深圳"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("湛江分公司");
////        user.setFrequency(softUserCount.getZj());
//        user.setUserCount(this.getUserCount(userDetails,"湛江"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("国际分公司");
////        user.setFrequency(softUserCount.getGj());
//        user.setUserCount(this.getUserCount(userDetails,"国际"));
//        softUserList.add(user);
//        user = new SoftUser();
//        user.setName("非常规油气分公司");
////        user.setFrequency(softUserCount.getFcgyq());
//        user.setUserCount(this.getUserCount(userDetails,"非常规"));
//        softUserList.add(user);
////        user = new SoftUser();
////        user.setName("其他");
////        user.setFrequency(softUserCount.getQt());
////        user.setUserCount(this.getUserCount(userDetails,"其他"));
////        softUserList.add(user);
//
//
//        return softUserList;
    }


    private Integer getUserCount(List<SoftUserDetails> userDetailsList , String city){
        for (SoftUserDetails details : userDetailsList){
            if (details.getName().equals(city)){
                return details.getCount();
            }
        }
        return 0;
    }

    public SoftContrast softContrast(String softName) {

        SoftContrast contrast = new SoftContrast();

        List<SoftContrastCount> contrastCountList = new ArrayList<>();

        if(!"prod".equals(env.getProperty("spring.profiles.active"))){
            contrastCountList = baseMapper.softContrastMysql(softName);
        }else{
            contrastCountList = baseMapper.softContrast(softName);
        }

        if (contrastCountList.size() == 0) {
            return contrast;
        }


        List<String> modelList = new ArrayList<>();

        List<Integer> bjList = new ArrayList<>();
        List<Integer> tjList = new ArrayList<>();
        List<Integer> shList = new ArrayList<>();
        List<Integer> szList = new ArrayList<>();
        List<Integer> zjList = new ArrayList<>();
        List<Integer> gjList = new ArrayList<>();
        List<Integer> fcgyqList = new ArrayList<>();
        List<Integer> qtList = new ArrayList<>();
        List<Integer> hyfzList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();

        LicenseSoftware software = this.getOne(new QueryWrapper<LicenseSoftware>().lambda().eq(LicenseSoftware::getSoftwarename,softName));
        if(software==null){
            return contrast;
        }

        QueryWrapper<SoftwareModuleSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SoftwareModuleSetting::getSoftwareid,software.getId()).eq(SoftwareModuleSetting::getIsshow,1);
        queryWrapper.select("licensename");//模块名称和许可名称不一样
        List<String> showLicNames = softwareModuleSettingService.listObjs(queryWrapper,Object::toString);

        for (SoftContrastCount count : contrastCountList) {
            if(showLicNames.size()==0 || showLicNames.contains(count.getLicenseName())){
                modelList.add(count.getLicenseName());
                bjList.add(count.getBj());
                tjList.add(count.getTj());
                shList.add(count.getSh());
                szList.add(count.getSz());
                zjList.add(count.getZj());
                gjList.add(count.getGj());
                fcgyqList.add(count.getFcgyq());
                qtList.add(count.getQt());
                hyfzList.add(count.getHyfz());
                int AllCount = count.getBj() + count.getTj() + count.getSh() + count.getSz() + count.getZj() + count.getGj() + count.getFcgyq() + count.getHyfz();
                countList.add(AllCount);
            }
        }

        contrast.setModelList(modelList);
        contrast.setBjList(bjList);
        contrast.setTjList(tjList);
        contrast.setShList(shList);
        contrast.setSzList(szList);
        contrast.setZjList(zjList);
        contrast.setGjList(gjList);
        contrast.setFcgyqList(fcgyqList);
        contrast.setQtList(qtList);
        contrast.setHyfzList(hyfzList);
        contrast.setCountList(countList);

        return contrast;

    }


    public List<SoftwareModuleSetting> softModule(String name){
        List<SoftwareModuleSetting> list =  moduleSettingMapper.softModule(name);
        return list;
    }

    public SoftContrast softUsage(String softwareName,
                          String moduleName,
                          String moduleId,
                          String startDate,
                          String endDate){
        SoftContrast contrast = new SoftContrast();

        List<SoftContrastCount> contrastCountList = new ArrayList<>();

        if(!"prod".equals(env.getProperty("spring.profiles.active"))){
            contrastCountList = baseMapper.softUsageMysql(softwareName,moduleName,startDate,endDate);
        }else{
            contrastCountList = baseMapper.softUsage(softwareName,moduleName,startDate,endDate);
        }


        Integer buyNum = baseMapper.getBuyNumber(moduleId);
        buyNum = buyNum ==null ? 0 : buyNum;

        List<String> modelList = new ArrayList<>();

        List<Integer> bjList = new ArrayList<>();
        List<Integer> tjList = new ArrayList<>();
        List<Integer> shList = new ArrayList<>();
        List<Integer> szList = new ArrayList<>();
        List<Integer> zjList = new ArrayList<>();
        List<Integer> gjList = new ArrayList<>();
        List<Integer> fcgyqList = new ArrayList<>();
        List<Integer> qtList = new ArrayList<>();
        List<Integer> hyfzList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();
        List<Integer> buyList = new ArrayList<>();

        for (SoftContrastCount count : contrastCountList) {
            modelList.add(count.getLicenseName());
            bjList.add(count.getBj());
            tjList.add(count.getTj());
            shList.add(count.getSh());
            szList.add(count.getSz());
            zjList.add(count.getZj());
            buyList.add(buyNum);
            gjList.add(count.getGj());
            fcgyqList.add(count.getFcgyq());
            qtList.add(count.getQt());
            hyfzList.add(count.getHyfz());
            int AllCount = count.getBj() + count.getTj() + count.getSh() + count.getSz() + count.getZj() + count.getGj() + count.getFcgyq() + count.getQt();
            countList.add(AllCount);
        }

        contrast.setModelList(modelList);
        contrast.setBjList(bjList);
        contrast.setTjList(tjList);
        contrast.setShList(shList);
        contrast.setSzList(szList);
        contrast.setZjList(zjList);
        contrast.setGjList(gjList);
        contrast.setFcgyqList(fcgyqList);
        contrast.setQtList(qtList);
        contrast.setHyfzList(hyfzList);
        contrast.setCountList(countList);
        contrast.setBuyList(buyList);

        return contrast;
    }

    public SoftRedNumber softNumber(){

        /**
         * 累计访问 与 本月访问做缓存
         */
        SoftRedNumber number = baseMapper.softNumber(DateUtils.formatDate());

        number.setAllVisitNum(allVisitNum);
        number.setMonthVisitNum(monthVisitNum);

        return number;
    }

    @Scheduled(fixedDelay=60*60*1000)   //每隔2小时执行
    public void setAllVisitNum() {
        System.out.println("执行allVisitNum");
        this.allVisitNum = baseMapper.getHistoryVisitCopy();
    }


    @Scheduled(fixedDelay=60*60*1000)   //每隔2小时执行
    public void setMonthVisitNum() {
        System.out.println("执行monthVisitNum");
        this.monthVisitNum = baseMapper.getHistoryVisit(DateUtils.getBeginMonth());;
    }


    public void SyncSoftwareUser(){

        realSoftUserMapper.deleteAll();

        List<SoftUserDetails> userDetails = baseMapper.softUserDetails("");
        RealSoftUser user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setName("北京分公司");
        user.setSort(1);
        user.setUserCount(this.getUserCount(userDetails,"北京"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setName("天津分公司");
        user.setSort(2);
        user.setUserCount(this.getUserCount(userDetails,"天津"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setName("上海分公司");
        user.setSort(3);
        user.setUserCount(this.getUserCount(userDetails,"上海"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setSort(4);
        user.setName("深圳分公司");
        user.setUserCount(this.getUserCount(userDetails,"深圳"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setSort(5);
        user.setName("湛江分公司");
        user.setUserCount(this.getUserCount(userDetails,"湛江"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setSort(6);
        user.setName("国际分公司");
        user.setUserCount(this.getUserCount(userDetails,"国际"));
        realSoftUserMapper.insert(user);
        user = new RealSoftUser();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setSort(7);
        user.setName("非常规油气分公司");
        user.setUserCount(this.getUserCount(userDetails,"非常规"));
        realSoftUserMapper.insert(user);
    }

}
